package com.zlk.algorithm.dataStructure;

import org.junit.Test;

import java.util.Arrays;

/**
 * @program: algorithm
 * @ClassName LogarithmTool
 * @description: 对数器  随机生成大样本数据进行算法验证
 * eg:验证插入  选择 排序是否正确
 * @author: slfang
 * @create: 2023-12-12 16:37
 * @Version 1.0
 **/
public class LogarithmTool {

    @Test
    public void test(){
        int maxLen = 50;
        int maxValue = 1000;
        int textTime = 10000;
        for (int i = 0; i < textTime; i++) {
            int[] arr1 = getRandomLenRandomValArr(maxLen,maxValue);
            int[] temp = copyArray(arr1);
            selectSort(arr1);
            if (!isSorted(arr1)){
                System.out.println(Arrays.toString(temp));
                System.out.println();
                System.out.println("选择排序错了！");
            }
        }

    }

    /**
     * 获取随机长度随机数值的数组
     * @return
     */
    public int[] getRandomLenRandomValArr(int maxLen,int maxVal){
        int len = (int)(Math.random()*maxLen);
        int[] arr = new int[len];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random()*maxVal);
        }
        return arr;
    }

    public static int[] copyArray(int[] arr){
        int[] ans = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            ans[i] = arr[i];
        }
        return ans;
    }

    //arr1和arr2一定是等长的
    public static boolean isSorted(int[] arr){
        if (arr.length < 2){
            return true;
        }
        int max = arr[0];
        for (int i = 0; i < arr.length; i++) {
            if (max > arr[i]){
                return false;
            }
            max = Math.max(max,arr[i]);
        }
        return true;
    }



    //选择排序方法
    public static void selectSort(int[] arr){
        //先想边界条件
        if (arr == null || arr.length<2){
            return;
        }
        int N = arr.length;
        for (int i = 0; i < N; i++) {
            int minValueIndex = i;
            for (int j = i + 1; j < N; j++){
                minValueIndex = arr[j] < arr[minValueIndex] ? j : minValueIndex;
            }
            swap(arr, i , minValueIndex);
        }
    }

    //冒泡排序方法
    public static void bubbleSort(int[] arr) {
        //先想边界条件
        if (arr == null || arr.length < 2) {
            return;
        }
        int N = arr.length;
        for (int end = N-1; end >= 0; end--){
            for (int second = 1; second <= end; second++) {
                if (arr[second - 1] > arr[second]) {
                    swap(arr,second - 1, second);
                }
            }
        }
    }

    //交换方法
    public static void swap(int[] arr, int i, int j ){
        int tmp = arr[j];
        arr[j] = arr[i];
        arr[i] = tmp;
    }





}
